package com.googlecode.likesql.converter;

import java.util.LinkedList;
import java.util.List;

import com.googlecode.likesql.constant.Keyword;
import com.googlecode.likesql.constant.SqlChar;
import com.googlecode.likesql.constant.SqlConstant;
import com.googlecode.likesql.expression.LikeExp;

/**
 * This object represents the converter to convert {@link com.googlecode.likesql.expression.LikeExp LikeExp}.
 * 
 * @author Johny Huang
 * @since 0.1
 */
public class LikeExpConverter implements Converter{

	public String toTemplate(Object obj) {
		LikeExp exp=(LikeExp)obj;
		StringBuffer sb=new StringBuffer().append(SqlConstant.CHAR_FOR_REPLACE);
		Character ch=exp.getEscapeChar();
		if(ch!=null){
			sb.append(SqlChar.SP)
			  .append(Keyword.ESCAPE)
			  .append(SqlChar.SP)
			  .append(SqlConstant.CHAR_FOR_REPLACE);
		}
		return sb.toString();
	}
	
	public String toSql(Object obj){
		LikeExp exp=(LikeExp)obj;
		StringBuffer sb=new StringBuffer();
		sb.append(SqlChar.QUOTE)
		  .append(exp.getExpression())
		  .append(SqlChar.QUOTE);
		Character ch=exp.getEscapeChar();
		if(ch!=null){
			sb.append(SqlChar.SP)
			  .append(Keyword.ESCAPE)
			  .append(SqlChar.SP)
			  .append(SqlChar.QUOTE)
			  .append(ch)
			  .append(SqlChar.QUOTE);
		}
		return sb.toString();
	}

	public List toValueList(Object obj) {
		LikeExp exp=(LikeExp)obj;
		LinkedList list=new LinkedList();
		list.add(exp.getExpression());
		if(exp.getEscapeChar()!=null){
			list.add(exp.getEscapeChar());
		}
		return list;
	}

}
